<template>
  <div class="container">
    <div class="sidebar"></div>
    <div class="content">
      <h1>审核报修单（只能看到待处理（未审批）的报修单）</h1>

      <!-- 搜索框 -->
      <div class="search-container">
        <input
            v-model="searchQuery"
            placeholder="搜索报修单"
            @input="debouncedSearch"
            @keyup.enter="handleSearch"
        />
        <button @click="handleSearch">搜索</button>
      </div>
      <button @click="exportToExcel">导出已审批报修单</button>

      <table v-if="filteredRepairs.length > 0" class="repair-table">
        <thead>
        <tr>
          <th>报修ID</th>
          <th>用户姓名</th>
          <th>类型</th>
          <th>标题</th>
          <th>报修时间</th>
          <th>状态</th>
          <th>操作</th>
        </tr>
        </thead>
        <tbody>
        <tr v-for="repair in paginatedRepairs" :key="repair.failureRepairId">
          <td>{{ repair.failureRepairId }}</td>
          <td>{{ repair.fullName }}</td>
          <td>{{ repair.type }}</td>
          <td>{{ repair.title }}</td>
          <td>{{ repair.repairTime }}</td>
          <td>{{ repair.repairStatus }}</td>
          <td>
            <button @click="reviewRepair(repair)">查看详情</button>
          </td>
        </tr>
        </tbody>
      </table>
      <p v-else>暂无待审核报修单。</p>

      <!-- 分页 -->
      <div class="pagination" v-if="totalPages > 1">
        <button
            v-for="page in totalPages"
            :key="page"
            :class="{ active: currentPage === page }"
            @click="changePage(page)"
        >
          {{ page }}
        </button>
      </div>

      <!-- 查看报修单详情的对话框 -->
      <div v-if="selectedRepair" class="repair-details-overlay">
        <div class="repair-details">
          <h2>报修单详情</h2>
          <p><strong>报修ID:</strong> {{ selectedRepair.failureRepairId }}</p>
          <p><strong>用户姓名:</strong> {{ selectedRepair.fullName }}</p>
          <p><strong>类型:</strong> {{ selectedRepair.type }}</p>
          <p><strong>标题:</strong> {{ selectedRepair.title }}</p>
          <p><strong>报修时间:</strong> {{ selectedRepair.repairTime }}</p>
          <p><strong>联系电话:</strong> {{ selectedRepair.contactNumber }}</p>
          <p><strong>维修地址:</strong> {{ selectedRepair.repairAddress }}</p>
          <p><strong>故障描述:</strong> {{ selectedRepair.faultDescription }}</p>
          <p><strong>状态:</strong> {{ selectedRepair.repairStatus }}</p>

          <button @click="approveRepair(selectedRepair.failureRepairId)">批准</button>
          <button @click="closeDetails">关闭</button>
        </div>
      </div>

      <!-- 通知区域 -->
      <div class="notifications" v-if="notifications.length > 0">
        <div class="notification" v-for="(notification, index) in notifications" :key="index">
          {{ notification.message }}
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue';
import axios from 'axios';
import SockJS from 'sockjs-client';
import Stomp from 'stompjs';

const repairList = ref([]);
const selectedRepair = ref(null);
const currentPage = ref(1);
const pageSize = 5;
const searchQuery = ref('');
const stompClient = ref(null);
const notifications = ref([]);

// 组件挂载时获取报修单数据和连接WebSocket
onMounted(() => {
  fetchRepairData();
  connectWebSocket();
});

// 组件卸载时断开WebSocket连接
onUnmounted(() => {
  if (stompClient.value) {
    stompClient.value.disconnect();
  }
});

// 获取报修单数据的异步函数
async function fetchRepairData() {
  try {
    const response = await axios.get('http://localhost:8001/failure-repair1/list', {
      params: {
        query: searchQuery.value
      }
    });
    console.log(response.data);  // 调试输出
    repairList.value = response.data.records.filter((repair) => repair.repairStatus !== '已审批');
  } catch (error) {
    console.error('获取报修数据时出错:', error);
  }
}

// 查看报修单详情
function reviewRepair(repair) {
  selectedRepair.value = { ...repair };
}

// 关闭报修单详情
function closeDetails() {
  selectedRepair.value = null;
}

// 批准报修单的异步函数
async function approveRepair(id) {
  try {
    await axios.put(`http://localhost:8001/failure-repair1/approve/${id}`);
    fetchRepairData();
    closeDetails();
  } catch (error) {
    console.error('批准报修单时出错:', error);
  }
}

// 计算总页数
const totalPages = computed(() => {
  return Math.ceil(filteredRepairs.value.length / pageSize);
});

// 获取当前页的报修单数据
const paginatedRepairs = computed(() => {
  const start = (currentPage.value - 1) * pageSize;
  const end = start + pageSize;
  return filteredRepairs.value.slice(start, end);
});

// 根据搜索查询过滤报修单
const filteredRepairs = computed(() => {
  const query = searchQuery.value.toLowerCase();
  return repairList.value.filter(repair => {
    return (
        repair.failureRepairId.toString().includes(query) ||
        repair.fullName.toLowerCase().includes(query) ||
        repair.type.toLowerCase().includes(query) ||
        repair.title.toLowerCase().includes(query)
    );
  });
});

// 改变当前页码
function changePage(page) {
  currentPage.value = page;
}

// 处理搜索输入
function debounce(fn, delay) {
  let timeoutID = null;
  return function () {
    clearTimeout(timeoutID);
    let args = arguments;
    let that = this;
    timeoutID = setTimeout(function () {
      fn.apply(that, args);
    }, delay);
  };
}

const debouncedSearch = debounce(handleSearch, 300);

function handleSearch() {
  currentPage.value = 1;
  fetchRepairData();
}

// 连接WebSocket
function connectWebSocket() {
  const socket = new SockJS('/ws');
  stompClient.value = Stomp.over(socket);

  stompClient.value.connect({}, frame => {
    console.log('Connected: ' + frame);

    stompClient.value.subscribe('/topic/repairs', message => {
      console.log('Received message:', message.body);

      // 添加新通知
      notifications.value.push({ message: message.body });

      // 移除旧通知（5秒后）
      setTimeout(() => {
        notifications.value.shift();
      }, 60000); // 5秒后自动移除
    });
  }, error => {
    console.error('WebSocket connection error:', error);
  });
}

async function exportToExcel() {
  try {
    const response = await axios.get('http://localhost:8001/failure-repair1/export', {
      responseType: 'blob' // 以blob的形式接收数据
    });
    const url = window.URL.createObjectURL(new Blob([response.data]));
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', 'approved_repairs.xlsx'); // 文件名
    document.body.appendChild(link);
    link.click();
    link.remove();
  } catch (error) {
    console.error('导出Excel时出错:', error);
  }
}
</script>

<style scoped>
.container {
  display: flex;
}

.sidebar {
  width: 1%;
  background-color: #f9f9f9;
}

.content {
  width: 99%;
  padding: 10px;
}

.repair-table {
  width: 100%;
  border-collapse: collapse;
  margin: 10px 0;
}

.repair-table th,
.repair-table td {
  border: 1px solid #ddd;
  padding: 8px;
  text-align: left;
}

.repair-table th {
  background-color: #f2f2f2;
  font-weight: bold;
}

.pagination {
  margin-top: 10px;
  display: flex;
  justify-content: center;
}

.pagination button {
  padding: 5px 10px;
  margin: 0 2px;
  border: none;
  background-color: #007bff;
  color: white;
  cursor: pointer;
  border-radius: 4px;
}

.pagination button.active {
  background-color: #0056b3;
}

.pagination button:hover {
  background-color: #0056b3;
}

.repair-details {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: white;
  border: 1px solid #ddd;
  padding: 20px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

.repair-details-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
}

.notifications {
  position: fixed;
  top: 0;
  right: 0;
  margin: 10px;
  max-width: 300px;
}

.notification {
  background: #f8d7da;
  color: #721c24;
  padding: 10px;
  margin-bottom: 5px;
  border-radius: 4px;
}
</style>
